package com.hefei.garden.config.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

/**
 * @author: devil
 * @Date: 2022/10/8 19
 * @Description:
 */
@Component
public class JedisUtils {

    @Autowired
    private JedisConfig jedisConfig;

    /**
     * 获取jedis对象
     */
    public Jedis getJedis(int... index) {
        Jedis jedis = jedisConfig.jedisPool().getResource();
        if (index != null && index.length > 0) {
            if (index[0] > 0 && index[0] <= 16) {
                jedis.select(index[0]);
            }
        }
        return jedis;
    }

    public String get(String key) {
        Jedis jedis = null;
        String value = null;
        try {
            jedis = getJedis();
            value = jedis.get(key);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return value;
    }

    public String setex(String key, String value, int seconds) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = getJedis();
            result = jedis.setex(key, seconds, value);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return result;
    }

}
